import ctypes
import time
from screeninfo import get_monitors

# Windows API 函数
user32 = ctypes.windll.user32
# 加载 kernel32
kernel32 = ctypes.windll.kernel32
Sleep = kernel32.Sleep

# 模拟鼠标左键按下和松开
MOUSEEVENTF_LEFTDOWN = 0x02
MOUSEEVENTF_LEFTUP = 0x04

def get_screen_resolution():
    """
    获取所有屏幕的分辨率信息。
    """
    monitors = get_monitors()
    resolutions = []
    for monitor in monitors:
        resolutions.append((monitor.width, monitor.height))
    return resolutions

def set_cursor_pos(x, y):
    """
    设置鼠标光标位置
    """
    user32.SetCursorPos(x, y)

def mouse_click(x, y):
    """
    在指定位置模拟鼠标点击操作
    """
    # 移动鼠标到指定位置
    set_cursor_pos(x, y)
    
    # 模拟鼠标左键按下
    user32.mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    time.sleep(0.1)  # 模拟点击的间隔时间
    # 模拟鼠标左键松开
    user32.mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0)

def click_mouse_at_position(position):
    """
    在指定位置按下并释放鼠标按钮（模拟鼠标点击）。
    
    :param position: 一个包含x, y坐标的元组 (x, y)
    """
    # 获取所有屏幕的分辨率
    screen_resolutions = get_screen_resolution()
    
    # 确保位置适合于某一屏幕
    for resolution in screen_resolutions:
        screen_width, screen_height = resolution
        # 如果坐标超出屏幕的宽高范围，就跳过此屏幕
        if position[0] <= screen_width and position[1] <= screen_height:
            # print(f"点击坐标: {position}, 屏幕分辨率: {screen_width}x{screen_height}")
            mouse_click(position[0], position[1])  # 执行鼠标点击
            break

def mouse_press(duration_ms):
    """
    模拟鼠标左键按下并保持指定时间后松开。

    :param duration_ms: 按下的持续时间，单位为毫秒。
    """
    # 模拟鼠标左键按下
    user32.mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    # 保持按下指定的时间
    Sleep(duration_ms)
    # 模拟鼠标左键松开
    user32.mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)

if __name__ == '__main__':
    # 假设鼠标需要点击的目标位置是 (x=1500, y=500)
    target_position = (500, 500)
    click_mouse_at_position(target_position)
    mouse_press(200)
